package com.giftmail.handler

import com.giftmail.message.RegisterMsg
import io.netty.buffer.{ByteBuf, Unpooled}
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}

class ClientHandler extends ChannelInboundHandlerAdapter{
  /**
    * 一旦与服务器建立连接,将被调用
    * @param ctx
    */
  override def channelActive(ctx: ChannelHandlerContext) = {
    println("已经与服务器连接上了...")

    //向服务端发送字符串
//    val content = "hello sever"
//    ctx.writeAndFlush(Unpooled.copiedBuffer(content.getBytes("UTF-8")))
    //改造:第一步
    //与服务端建立RPC通信,传递case class数据
    ctx.writeAndFlush(RegisterMsg("hello sever"))
  }

  override def channelRead(ctx: ChannelHandlerContext, msg: scala.Any) = {
    println("channelRead invoke")
    val byteBuf = msg.asInstanceOf[ByteBuf]
    val bytes = new Array[Byte](byteBuf.readableBytes())
    byteBuf.readBytes(bytes)
    val message = new String(bytes,"UTF-8")
    println(message)
  }

  override def channelReadComplete(ctx: ChannelHandlerContext) = {
    println("channelReadComplete invoke....")
    ctx.flush()
  }

  override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) = {
    println("exceptionCaught invoke....")
    ctx.close()
  }
}
